﻿package com.autolinq.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import sun.misc.BASE64Decoder;

import com.autolinq.pojo.WeChatMessage;
import com.autolinq.util.http.HttpPostMessage;

/**
 * 
 * 微信所有接口入口
 * 
 * @author slz
 * 
 *         2013-7-26 上午11:01:08
 */

public class PushManage {
	Logger logger = Logger.getLogger(this.getClass().getName());
	
	public static byte[] readStream(InputStream inStream) throws Exception {  
	    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
	    byte[] buffer = new byte[10240];  
	    int len = -1;  
	    while ((len = inStream.read(buffer)) != -1) {  
	    	System.out.println("len=="+len); 
	        outSteam.write(buffer, 0, len);  
	    }  
	    outSteam.close();  
	    inStream.close();  
	    return outSteam.toByteArray();  
	}  
	
	public String PushManageXml(InputStream is,String qrcodePath,Properties prop) throws JDOMException {

		String returnStr = "";
		String toName = "";
		String fromName = "";
		String type = "";
		String content = "";
		String con = "";		
		String deviceType = "";		
		String sessionId = "";		
		String deviceId = "";
		String openId = "";
		String msgId = "";
		String event = "";// 自定义按钮事件请求
		String eKey = "";// 事件请求key值

		try {
			System.out.println("date:"+new Date());

			SAXBuilder sax = new SAXBuilder();

			Document doc = sax.build(is);

			// 获得文件的根元素

			Element root = doc.getRootElement();

			// 获得根元素的第一级子节点

			List list = root.getChildren();

			for (int j = 0; j < list.size(); j++) {

				// 获得结点

				Element first = (Element) list.get(j);

				if (first.getName().equals("ToUserName")) {

					toName = first.getValue().trim();
					System.out.println("toName:"+toName);
					logger.debug("toName:"+toName);
				} else if (first.getName().equals("FromUserName")) {

					fromName = first.getValue().trim();
					logger.debug("fromName:"+fromName);
					System.out.println("fromName:"+fromName);
				} else if (first.getName().equals("MsgType")) {

					type = first.getValue().trim();
					logger.debug("MsgType:"+type);
					System.out.println("MsgType:"+type);
				} else if (first.getName().equals("Content")) {

					con = first.getValue().trim();
					logger.debug("Content:"+con);
					System.out.println("Content:"+con);
				} else if (first.getName().equals("Event")) {

					event = first.getValue().trim();
					System.out.println("Event:"+event);
				} else if (first.getName().equals("EventKey")) {

					eKey = first.getValue().trim();
					System.out.println("EventKey:"+eKey);
				}else if (first.getName().equals("DeviceType")) {

					deviceType = first.getValue().trim();

				} else if (first.getName().equals("SessionID")) {

					sessionId = first.getValue().trim();

				} else if (first.getName().equals("DeviceID")) {

					deviceId = first.getValue().trim();
					logger.debug("DeviceID:"+deviceId);
					System.out.println("DeviceID:"+deviceId);
				}  else if (first.getName().equals("OpenID")) {

					openId = first.getValue().trim();
					logger.debug("OpenID:"+openId);
					System.out.println("OpenID:"+openId);
				} else if (first.getName().equals("MsgID")) {

					msgId = first.getValue().trim();
					logger.debug("MsgID:"+msgId);
					System.out.println("MsgID:"+msgId);
				}

			}

		} catch (Exception e) {

			e.printStackTrace();

		}
		//这里可以写一个接口,根据不同的type进行不同的处理
		if (type.equals("device_type")) {
			// handle message which sends from device 
			returnStr = handleDeviceMessage(con,fromName,toName,deviceType,deviceId,sessionId,qrcodePath,openId,msgId,prop);
		}else if (type.equals("device_event")) {
			// handle message which sends from device 
			returnStr = handleDeviceEventMessage(con,fromName,toName,deviceType,deviceId,sessionId,qrcodePath,openId,event,type,prop);
		} else if (type.equals("event")) {
			System.out.println("type In:"+type);
			System.out.println("event In:"+event);
			System.out.println("eKey In:"+eKey);
			if (event.equals("subscribe")) {// 此为关注事件

				content = "您好，欢迎关注我！";

			}else if (event.toLowerCase().equals("click")) {
				// 以下为自定义按钮事件
				
				if (eKey.equals("music")) {// 音乐请求
					System.out.println("eKey In is:"+eKey);
					returnStr = getBackXMLTypeMusic(toName, fromName, content);
		
				} else if (eKey.equals("img")) {// 图片请求
		
					returnStr = getBackXMLTypeImg(toName, fromName, content);
		
				} else if (eKey.equals("trip")) {// 旅程按钮
		
					//returnStr = getBackXMLTypeTripList(toName, fromName, content);
		
				} else {// 无自定义按钮返回上面的文本信息
		
					returnStr = getBackXMLTypeText(toName, fromName, content);
		
				}
			}

		} else if (type.equals("text")) {

			if (con.equals("help") || con.equals("帮助") || con.equals("?")
					|| con.equals("？")) {

				content = "帮助中心\n\n";

			} else if (con.equals("bind") || con.equals("绑定")) {

				// content = "点击 <A \'\'" target=_blank>绑定账户</A>";

			} else if (con.startsWith("ck") || con.startsWith("CK")) {

				String order_id = "0";

				con.toLowerCase();

				if (con.startsWith("ck")) {

					order_id = con.substring(con.indexOf("ck") + 2);

				} else if (con.startsWith("CK")) {

					order_id = con.substring(con.indexOf("CK") + 2);

				}

				if (!"".equals(order_id)) {

					StringBuffer sb = new StringBuffer();

					sb.append("订单详情...\n");

					content = sb.toString();

				} else {

					content = "未查询到相应信息,请重新输入！";

				}

			}

		}
		return returnStr;

	}

	public String getBackXMLTypeText(String toName, String FromName,
			String content) {

		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(FromName));

		rootXML.addContent(new Element("FromUserName").setText(toName));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("text"));

		rootXML.addContent(new Element("Content").setText(content));

		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;

	}

	public String getBackXMLTypeImg(String toName, String FromName,
			String content) {

		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(FromName));

		rootXML.addContent(new Element("FromUserName").setText(toName));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("news"));

		rootXML.addContent(new Element("ArticleCount").setText("3"));

		Element fXML = new Element("Articles");

		Element mXML = null;

		String url = "";

		String ss = "";

		for (int i = 1; i <= 3; i++) {

			mXML = new Element("item");

			mXML.addContent(new Element("Title").setText("图片" + i));

			mXML.addContent(new Element("Description").setText("美女" + i));

			mXML.addContent(new Element("PicUrl").setText(ss));

			mXML.addContent(new Element("Url").setText(url));

			fXML.addContent(mXML);

		}

		rootXML.addContent(fXML);

		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;

	}
	
	public String getBackXMLTypeTripList(WeChatMessage message) {

		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(message.getFromUserName()));

		rootXML.addContent(new Element("FromUserName").setText(message.getToUserName()));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("news"));

		rootXML.addContent(new Element("ArticleCount").setText("3"));

		Element fXML = new Element("Articles");

		Element mXML = new Element("item");
		mXML.addContent(new Element("Title").setText("结伴出游1.0"));
		mXML.addContent(new Element("Description").setText(""));
		mXML.addContent(new Element("PicUrl").setText("http://115.28.109.130/autoLinQ/img/big_pic.png"));
		mXML.addContent(new Element("Url").setText("http://115.28.109.130/autoLinQ/trip_list.html?openid="+(message.getOpenID()==null?message.getFromUserName():"")));
		fXML.addContent(mXML);
		
		Element mXML2 = new Element("item");
		mXML2.addContent(new Element("Title").setText("我的旅程"));
		mXML2.addContent(new Element("Description").setText(""));
		mXML2.addContent(new Element("PicUrl").setText("http://115.28.109.130/autoLinQ/img/trip.png"));
		mXML2.addContent(new Element("Url").setText("http://115.28.109.130/autoLinQ/trip_list.html?openid="+(message.getOpenID()==null?message.getFromUserName():"")));
		fXML.addContent(mXML2);
		
		Element mXML3 = new Element("item");
		mXML3.addContent(new Element("Title").setText("添加旅程"));
		mXML3.addContent(new Element("Description").setText(""));
		mXML3.addContent(new Element("PicUrl").setText("http://115.28.109.130/autoLinQ/img/add_ico.png"));
		mXML3.addContent(new Element("Url").setText("http://115.28.109.130/autoLinQ/add_trip.html?openid="+(message.getOpenID()==null?message.getFromUserName():"")));
		fXML.addContent(mXML3);

		rootXML.addContent(fXML);

		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;

	}
	
	public String getWechatWelcomePage(WeChatMessage message) {

		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(message.getFromUserName()));

		rootXML.addContent(new Element("FromUserName").setText(message.getToUserName()));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("news"));

		rootXML.addContent(new Element("ArticleCount").setText("4"));

		Element fXML = new Element("Articles");

		Element mXML = new Element("item");
		mXML.addContent(new Element("Title").setText("结伴出游1.0"));
		mXML.addContent(new Element("Description").setText(""));
		mXML.addContent(new Element("PicUrl").setText("http://115.28.109.130/autoLinQ/img/big_pic.png"));
		mXML.addContent(new Element("Url").setText("http://115.28.109.130/autoLinQ/trip_list.html?openid="+(message.getOpenID()==null?message.getFromUserName():"")));
		fXML.addContent(mXML);
		
		Element mXML2 = new Element("item");
		mXML2.addContent(new Element("Title").setText("旅程"));
		mXML2.addContent(new Element("Description").setText(""));
		mXML2.addContent(new Element("PicUrl").setText("http://115.28.109.130/autoLinQ/img/trip.png"));
		mXML2.addContent(new Element("Url").setText("http://115.28.109.130/autoLinQ/trip_list.html?openid="+(message.getOpenID()==null?message.getFromUserName():"")));
		fXML.addContent(mXML2);
		
		Element mXML3 = new Element("item");
		mXML3.addContent(new Element("Title").setText("搭车"));
		mXML3.addContent(new Element("Description").setText(""));
		mXML3.addContent(new Element("PicUrl").setText("http://115.28.109.130/autoLinQ/img/car.png"));
		mXML3.addContent(new Element("Url").setText("http://115.28.109.130/autoLinQ/add_trip.html?openid="+(message.getOpenID()==null?message.getFromUserName():"")));
		fXML.addContent(mXML3);
		
		Element mXML4 = new Element("item");
		mXML4.addContent(new Element("Title").setText("我的"));
		mXML4.addContent(new Element("Description").setText(""));
		mXML4.addContent(new Element("PicUrl").setText("http://115.28.109.130/autoLinQ/img/me.png"));
		mXML4.addContent(new Element("Url").setText("http://115.28.109.130/autoLinQ/add_trip.html?openid="+(message.getOpenID()==null?message.getFromUserName():"")));
		fXML.addContent(mXML4);

		rootXML.addContent(fXML);

		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;

	}

	public String getBackXMLTypeMusic(String toName, String FromName,
			String content) {

		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(FromName));

		rootXML.addContent(new Element("FromUserName").setText(toName));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("music"));

		Element mXML = new Element("Music");

		mXML.addContent(new Element("Title").setText("音乐"));

		mXML.addContent(new Element("Description").setText("音乐让人心情舒畅！"));

		mXML.addContent(new Element("MusicUrl").setText(content));

		mXML.addContent(new Element("HQMusicUrl").setText(content));

		rootXML.addContent(mXML);

		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;

	}
	
	public String handleDeviceMessage(WeChatMessage message,Properties prop,String path) {
		String contentDec = getFromBASE64(message.getContent());
		JSONObject jo = JSONObject.fromObject(contentDec);
		
		String funcID = (String)jo.get("FuncID");
		
		String json = "{\"Source\":\"MRN\"}";
		JSONObject jsonObj = JSONObject.fromObject(json);
		jsonObj.put("FunctionID", funcID);
		jsonObj.put("OpenID", message.getOpenID());
		jsonObj.put("DeviceID", message.getDeviceID());
		jsonObj.put("Message", jo);
		
		String contentRes = "";
		if("Init".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaInitURL"), jsonObj.toString());
		}else if("InitCheck".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaInitCheckURL"), jsonObj.toString());
		}else if("GetActiveTripInfo".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaGetActiveTripInfoURL"), jsonObj.toString());
		}else if("RetrieveDynamicInfo".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaRetrieveDynamicInfoURL"), jsonObj.toString());
		}else if("TerminateCoDriveTrip".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaTerminateCoDriveTripURL"), jsonObj.toString());
		}else if("TerminateCoDriveTrip".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaTerminateCoDriveTripURL"), jsonObj.toString());
		}else if("CoDriveTripAck".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaCoDriveTripAckURL"), jsonObj.toString());
		}else if("HeartPulse".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaHeartPulseURL"), jsonObj.toString());
		}
		
		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());
		String timeLong = String.valueOf(new Date().getTime());
		times = timeLong.substring(0, timeLong.length()-3);

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(message.getFromUserName()));
		rootXML.addContent(new Element("FromUserName").setText(message.getToUserName()));
		rootXML.addContent(new Element("CreateTime").setText(times));
		rootXML.addContent(new Element("MsgType").setText("device_text"));	
		rootXML.addContent(new Element("DeviceType").setText(message.getDeviceType()));
		rootXML.addContent(new Element("DeviceID").setText(message.getDeviceID()));
		rootXML.addContent(new Element("SessionID").setText(message.getSessionID()));
		//writeFile(contentRes,path,"beforebase64");
		String contentBase64 = getBASE64(contentRes);
		rootXML.addContent(new Element("Content").setText(contentBase64));	
		//writeFile(getBASE64(contentBase64),path,"afterbase64");
			
		//rootXML.addContent(new Element("MsgID").setText(message.getMsgID()));
		//rootXML.addContent(new Element("OpenID").setText(message.getOpenID()));
		
		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);
		
		//writeFile(getBASE64(returnStr),path,"all");
		if(returnStr!=null && returnStr.length()>38){
			returnStr = returnStr.substring(38);
		}
		return returnStr;
	}
	
	private void writeFile(String content,String path,String filename){
		FileOutputStream out = null;   


        int count=1000;//写文件行数   

        try {   

            out = new FileOutputStream(new File(path+filename+".txt"));   

            long begin = System.currentTimeMillis();   


                out.write(content.getBytes());   


            out.close();   

            long end = System.currentTimeMillis();   

        } catch (Exception e) {   

            e.printStackTrace();   

        }   

        finally {   

            try {      

                out.close();   

            } catch (Exception e) {   

                e.printStackTrace();   

            }   

        } 
	}

	private String handleDeviceMessage(String content,String fromName,String toName,String deviceType,String deviceId,
			String sessionId,String qrcodePath,String openId,String msgId,Properties prop) {
		String contentDec = getFromBASE64(content);
		
		//contentDec = contentDec.substring(7, contentDec.length());
		JSONObject jo = JSONObject.fromObject(contentDec);
		
		String appID = (String)jo.get("AppID");
		String funcID = (String)jo.get("FuncID");
		String appVersion = (String)jo.get("AppVersion");
		Integer sessionID = (Integer)jo.get("SessionID");
		JSONObject data = (JSONObject)jo.get("Data");
		
		String json = "{\"Source\":\"MRN\"}";
		JSONObject jsonObj = JSONObject.fromObject(json);
		jsonObj.put("FunctionID", funcID);
		jsonObj.put("OpenID", openId);
		jsonObj.put("DeviceID", deviceId);
		jsonObj.put("Message", jo);
		
		String contentRes = "";
		if("Init".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaInitURL"), jsonObj.toString());
		}else if("InitCheck".equals(funcID)){
			contentRes = HttpPostMessage.postMessage(prop.getProperty("otaInitCheckURL"), jsonObj.toString());
		}
		
		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());
		String timeLong = String.valueOf(new Date().getTime());
		times = timeLong.substring(0, timeLong.length()-3);

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(fromName));
		rootXML.addContent(new Element("FromUserName").setText(toName));
		rootXML.addContent(new Element("CreateTime").setText(times));
		rootXML.addContent(new Element("MsgType").setText("device_text"));	
		rootXML.addContent(new Element("DeviceType").setText(deviceType));
		rootXML.addContent(new Element("DeviceID").setText(deviceId));
		rootXML.addContent(new Element("Content").setText(getBASE64(contentRes)));		
		rootXML.addContent(new Element("SessionID").setText(sessionId));	
		rootXML.addContent(new Element("MsgID").setText(sessionId));
		rootXML.addContent(new Element("OpenID").setText(openId));
		
		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;
	}
	
	private String handleDeviceEventMessage(String content,String fromName,String toName,String deviceType,String deviceId,
			String sessionId,String qrcodePath,String openId,String event,String msgType,Properties prop) {
		
		HttpPostMessage.postMessage(prop.getProperty("bindURL"), "openId="+openId+"&deviceId="+deviceId);
		
		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(fromName));

		rootXML.addContent(new Element("FromUserName").setText(toName));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("device_text"));
		
		rootXML.addContent(new Element("Event").setText(event));
		
		rootXML.addContent(new Element("DeviceType").setText(deviceType));

		rootXML.addContent(new Element("DeviceId").setText(deviceId));

		rootXML.addContent(new Element("SessionId").setText(sessionId));
		
		rootXML.addContent(new Element("Content").setText(content));
		
		rootXML.addContent(new Element("OpenID").setText(openId));
		
		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;
	}
	
	public String handleDeviceEventMessage(WeChatMessage message,Properties prop) {
		
		if(message.getEvent().toLowerCase().equals("bind")){
			HttpPostMessage.postMessage(prop.getProperty("bindURL"), "openId="+message.getOpenID()+"&deviceId="+message.getDeviceID());
		}
		
		
		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());
		String timeLong = String.valueOf(new Date().getTime());
		times = timeLong.substring(0, timeLong.length()-3);

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(message.getFromUserName()));

		rootXML.addContent(new Element("FromUserName").setText(message.getToUserName()));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("device_event"));
		
		rootXML.addContent(new Element("Event").setText(message.getEvent()));
		
		rootXML.addContent(new Element("DeviceType").setText(message.getDeviceType()));

		rootXML.addContent(new Element("DeviceId").setText(message.getDeviceID()));

		rootXML.addContent(new Element("SessionId").setText(message.getSessionID()));
		
		rootXML.addContent(new Element("Content").setText(message.getContent()));
		
		rootXML.addContent(new Element("OpenID").setText(message.getOpenID()));
		
		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;
	}
	
	public String handleWechatEventMessage(WeChatMessage message,Properties prop) {
		
		HttpPostMessage.postMessage(prop.getProperty("subscribeURL"), "openId="+message.getFromUserName());
		
		String returnStr = "";

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

		String times = format.format(new Date());

		Element rootXML = new Element("xml");

		rootXML.addContent(new Element("ToUserName").setText(message.getFromUserName()));

		rootXML.addContent(new Element("FromUserName").setText(message.getToUserName()));

		rootXML.addContent(new Element("CreateTime").setText(times));

		rootXML.addContent(new Element("MsgType").setText("device_text"));
		
		rootXML.addContent(new Element("Event").setText(message.getEvent()));
		
		rootXML.addContent(new Element("DeviceType").setText(message.getDeviceType()));

		rootXML.addContent(new Element("DeviceId").setText(message.getDeviceID()));

		rootXML.addContent(new Element("SessionId").setText(message.getSessionID()));
		
		rootXML.addContent(new Element("Content").setText(message.getContent()));
		
		rootXML.addContent(new Element("OpenID").setText(message.getOpenID()));
		
		Document doc = new Document(rootXML);

		XMLOutputter XMLOut = new XMLOutputter();

		returnStr = XMLOut.outputString(doc);

		return returnStr;
	}

	// 将 s 进行 BASE64 编码
	public static String getBASE64(String s) {
		if (s == null)
			return null;
		//return new String(org.apache.commons.codec.binary.Base64.encodeBase64(s.getBytes(),false));
		return new String(org.apache.commons.codec.binary.Base64.encodeBase64(s.getBytes()));
		//return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
	}

	// 将 BASE64 编码的字符串 s 进行解码
	public static String getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b);
		} catch (Exception e) {
			return null;
		}
	}

}